package commucation;
import javax.jms.*;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerPlugin;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.network.NetworkConnector;
import org.apache.activemq.security.JaasAuthenticationPlugin;

public class MessagesReceiver {
    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    private TerrainMessageListener listener = new TerrainMessageListener();
    
    public TerrainMessageListener getListener(){
    	return listener;
    }

    public void listenOn(String topicName) throws JMSException {

    	BrokerService broker = new BrokerService();
    	try {
			broker.addConnector("tcp://localhost:61616");
			broker.addConnector("tcp://localhost:61617");
			broker.addConnector("tcp://localhost:61618");
			broker.addConnector("tcp://localhost:61618");
			broker.setBrokerName("messageReceiver");
			broker.setUseShutdownHook(false);
		} catch (Exception e) {
			System.out.println("Erreur d'ajout du connecteur");
			e.printStackTrace();
		}
    	try {
			broker.start();
		} catch (Exception e) {
			System.out.println("Erreur de lancement du broker");
			e.printStackTrace();
		}
    	
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);

        Topic topic = session.createTopic(topicName);

        MessageConsumer consumer = session.createConsumer(topic);

        
        
        consumer.setMessageListener(listener);
        System.out.println("Attente des messages d'incidents ...");

    }
}